import React from 'react'
import { Upload, Button, message } from 'antd'
import { batchGetTmpHttpUrl, saveStoreInfo } from '~/api/store-file-api'
import { UploadOutlined } from '@ant-design/icons'
import { OssConfig } from 'public/config'

// eslint-disable-next-line @typescript-eslint/no-var-requires
const OSS = require('ali-oss')
//
export const putObject = async ({ files, fileType, option, frontend, onSuccess, note }: any) => {
  console.log('files', files)
  // const { data: config } = await getAssumeRoleInfo({})
  const uuid = new Date().getTime()
  const dateStr = new Date().toISOString().substr(0, 10)
  const client = new OSS(OssConfig)
  try {
    // alert(dateStr);
    const result = await client.put(frontend + dateStr + '/' + uuid + '.' + fileType, files, { mime: files.type })
    // alert(result.name);
    if (option) {
      option.onProgress({ percent: 100 })
      option.onSuccess()
    }

    const { data } = await saveStoreInfo({
      fileBucket: 'fz-wssp',
      fileName: result.name,
      // fileName: `${frontend}/`+dateStr+'/' + uuid + '.' + fileType,
      storeNote: note
    })

    const res = await batchGetTmpHttpUrl([data.storeId])
    onSuccess &&
    onSuccess({
      resultData: res.data && res.data.length && res.data[0],
      storeId: data.storeId,
      name: result.name,
      files,
      imgUrl: res.data[0].tmpHttpUrl
    })
    return { ...data, ...res.data[0] }
  } catch (e) {
    console.log(e)
  }
}

const MyUpload = ({ frontend, onSuccess, onRemove, note, title = '点击上传', ...props }: any) => {
  const onUpload = async (option: any) => {
    const files = option.file
    const type = files.type
    let fileType
    switch (type) {
      case 'image/png':
        fileType = 'png'
        break
      case 'image/jpeg':
        fileType = 'jpeg'
        break
      case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
        fileType = 'docx'
        break
      case 'application/pdf':
        fileType = 'pdf'
        break
      default:
        break
    }

    if (type.includes('png') || type.includes('jpeg') || type.includes('document') || type.includes('pdf')) {
      putObject({ files, frontend, fileType, option, onSuccess, note })
    } else {
      message.error('请选择png jpeg docx pdf 类型的文件')
    }
  }

  const onChange = (option: any) => {
    console.log('option', option)
    onUpload(option)
  }

  const beforeUpload = (file: any) => {
    const isLt2M = file.size / 1024 / 1024 < 1
    if (!isLt2M) {
      message.error('文件大小不能超过 1 MB')
      return false
    }
    return true
  }

  return (
    <Upload {...props} multiple={true} beforeUpload={beforeUpload} onRemove={onRemove} customRequest={onChange}>
      {props.children ? props.children : <Button icon={<UploadOutlined />}>{title}</Button>}
    </Upload>
  )
}

export default MyUpload
